from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.user import User
import base64
import io
import uuid
import os
import oss2

user_bp = Blueprint('user', __name__)

# 阿里云OSS配置
OSS_ACCESS_KEY_ID = os.environ.get('OSS_ACCESS_KEY_ID', 'your_access_key_id')
OSS_ACCESS_KEY_SECRET = os.environ.get('OSS_ACCESS_KEY_SECRET', 'your_access_key_secret')
OSS_BUCKET_NAME = os.environ.get('OSS_BUCKET_NAME', 'your_bucket_name')
OSS_ENDPOINT = os.environ.get('OSS_ENDPOINT', 'oss-cn-hangzhou.aliyuncs.com')
OSS_BUCKET_URL = f'https://{OSS_BUCKET_NAME}.{OSS_ENDPOINT}'

@user_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    return jsonify(user.to_dict()), 200

@user_bp.route('/profile', methods=['PUT'])
@jwt_required()
def update_profile():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    
    # 检查昵称唯一性
    if data.get('nickname') and data['nickname'] != user.nickname:
        if User.query.filter_by(nickname=data['nickname']).first():
            return jsonify({'message': '昵称已存在'}), 400
    
    # 检查手机号唯一性
    if data.get('phone') and data['phone'] != user.phone:
        if User.query.filter_by(phone=data['phone']).first():
            return jsonify({'message': '手机号已存在'}), 400
    
    # 检查邮箱唯一性
    if data.get('email') and data['email'] != user.email:
        if User.query.filter_by(email=data['email']).first():
            return jsonify({'message': '邮箱已存在'}), 400
    
    # 更新用户信息
    try:
        # 不允许修改用户名
        if 'username' in data:
            del data['username']
        
        # 特殊处理头像上传
        if 'avatar' in data and data['avatar']:
            avatar_data = data['avatar']
            # 如果是Base64数据，上传到OSS
            if avatar_data.startswith('data:image'):
                oss_url = upload_avatar_from_base64(avatar_data)
                if oss_url:
                    data['avatar'] = oss_url
                else:
                    # 如果上传失败，保持原头像或设置为空
                    data['avatar'] = user.avatar if user.avatar else ''
            # 如果已经是URL，则直接使用
            elif avatar_data.startswith('http'):
                data['avatar'] = avatar_data
            # 其他情况保持原样
            else:
                data['avatar'] = user.avatar if user.avatar else ''
        
        # 更新其他字段
        for key, value in data.items():
            if hasattr(user, key) and key != 'id' and key != 'password':
                setattr(user, key, value)
        
        db.session.commit()
        return jsonify({
            'message': '个人信息更新成功',
            'user': user.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

def upload_avatar_from_base64(base64_data):
    """
    从Base64数据上传头像到阿里云OSS
    """
    try:
        # 移除Base64数据URL前缀（如果存在）
        if base64_data.startswith('data:image'):
            # 提取文件扩展名
            if 'jpeg' in base64_data or 'jpg' in base64_data:
                extension = 'jpg'
            elif 'png' in base64_data:
                extension = 'png'
            elif 'gif' in base64_data:
                extension = 'gif'
            else:
                extension = 'jpg'  # 默认jpg
            
            # 分割数据并获取实际的Base64数据
            base64_data = base64_data.split(',')[1]
        else:
            # 如果没有前缀，默认使用jpg
            extension = 'jpg'
        
        # 解码Base64数据
        image_data = base64.b64decode(base64_data)
        
        # 生成随机文件名
        random_filename = f"{uuid.uuid4().hex}.{extension}"
        
        try:
            # 初始化阿里云OSS客户端
            auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
            bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)
            
            # 上传文件到OSS
            object_name = f"avatar/{random_filename}"
            result = bucket.put_object(object_name, io.BytesIO(image_data))
            
            if result.status == 200:
                # 构造访问URL
                avatar_url = f"{OSS_BUCKET_URL}/{object_name}"
                return avatar_url
            else:
                return None
        except Exception as e:
            print(f"上传到阿里云OSS失败: {str(e)}")
            return None
    
    except Exception as e:
        print(f"上传头像失败: {str(e)}")
        return None